import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  Animated,
  InteractionManager,
} from 'react-native';

import CommonViewPagerOne from '../common/CommonViewPagerOne';
import TImage from '../../components/TImage';
import SizeUtils from '../../common/SizeUtils';
import ToastUtils from '../../common/ToastUtils';
import ImageConstants from '../../common/ImageConstants';
import {DateUtils} from '../../utils/Utils';
import CommonStyles from '../../common/CommonStyles';
import Constants from '../../common/Constants';
import Config from '../../config';
import BaseItem from '../common/BaseItem';
import QuanziPostListView from './QuanziPostListView';
import QZ_QunliaoListView from './QZ_QunliaoListView';
import BasePage from '../common/BasePage';
import RequestQuanziContentAction from '../../actions/quanzi/RequestQuanziContentAction';
import QuanziSendShoucangQuanziAction from '../../actions/quanzi/QuanziSendShoucangQuanziAction';
import QZ_DetailAction from '../../actions/quanzi/QZ_DetailAction';
import CommonCheckUserTypeAction from '../../actions/common/CommonCheckUserTypeAction';
import Platform from 'Platform';
import CommonAvatarView from '../common/CommonAvatarView';
import Popover from '../common/Popover';
import PopoverConent from '../common/PopoverConent';
const topArr=[{name:'审帖',key:'review'},];

const BTN_LABELS = ["话题", "群聊"];
export default class QuanziContentPage extends BasePage {
  constructor(props) {
    super(props);
    this._pageWidth = SizeUtils.getWindowSize().width;
    this._headerHeight = SizeUtils.translateDesignHeightToCode(400);
    this._headerHeight_1 = SizeUtils.translateDesignHeightToCode(0);
    this._pageHeight = SizeUtils.getWindowSize().height;
    this._updateheaderTopTimer = null;

    this.state.componentReady = false;
    this.state.contentData = this.props.pageData.routeData;
    this.state.showType = 0;
    this.state.updateMark = 0;
    this.state.scrollEnabled = Platform.OS === 'ios';
    this.state.headerTop = new Animated.Value(0);
    this._headerTop = 0;
    this.state.scrollViewTop = new Animated.Value(this._headerHeight);

  }
  componentDidMount() {
    InteractionManager.runAfterInteractions(()=>{
      this.setState({
        componentReady: true,
      })
      new QZ_DetailAction().call(this, {board_id:this.state.contentData.board_id})
      this._requestData();
    })
  }
   _requestData() {
    new RequestQuanziContentAction().call(this, {board_id:this.state.contentData.board_id})
  }

  _dealLeavePage() {
    this._clearClickTopBtnTimer();
    this._clearUpdateheaderTopTimer();
    // this._scrollView.scrollTo({x: 0, animated: false});
    // this.state.showType = 0;
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);
    if(nextState.isResponeUpdate) {
        nextState.isResponeUpdate = false;
        if(this.state.contentData.is_favorited === 0) {
          ToastUtils.show("成功加入圈子");
          this.state.contentData.is_favorited = 1;
        }
        else {
          ToastUtils.show("成功退出圈子");
          this.state.contentData.is_favorited = 0;
          this.goBack();
        }
        // this.state.contentData.is_favorited = !this.state.contentData.is_favorited
        //  ||this.state.contentData.is_favorited == 0 ? 1 : 0;
        this._requestData();
    }

  }

  _dealEnterPage() {
    if(this.state.contentData){
      this.state.contentData = this.props.pageData.routeData;
      this._requestData();
      new QZ_DetailAction().call(this, {board_id:this.state.contentData.board_id})
      this.state.updateMark = this.state.updateMark + 1;
      this.state.headerTop = new Animated.Value(0);
      this._headerTop = 0;
      this.state.scrollViewTop = new Animated.Value(Config.paddingTop + this._headerHeight);
    }
  }
  _PopoverPress(key){
    this._closePopover();
    if ('review'===key) {
      this.gotoPage(Config.pages.quanzi_review)
    }
  }
  _closePopover(){
    this.setState({isVisible: false});
  }
  _showMoreRightBtn(buttonRect){
    this._popoverbtn.measure((ox, oy, width, height, px, py) => {
         this.setState({
              isVisible: true,
              buttonRect:buttonRect
          });
      });
  }
  render() {
    if (this.state.componentReady === false) {
      return<View/>
    }
    var displayArea = {x: 0, y: 0, width: SizeUtils.getWindowSize().width-10, height: 260};
    return(
      <View style={{backgroundColor:"#ffffff",
          width:SizeUtils.getWindowSize().width,
          height:SizeUtils.getWindowSize().height,}}>
        {this._getPage(0)}
        {this._renderNavigationBar()}
        {this._renderWriteButton()}
        <Popover
            isVisible={this.state.isVisible}
            fromRect={this.state.buttonRect}
            placement={'bottom'}
            isWhite={true}
            arrowSize={{height:10,width:15}}
            displayArea={displayArea}
            onClose={this._closePopover.bind(this)}>
            <View style={{width: 160,height: 40,backgroundColor:'transparent',}}>
              <PopoverConent titleArr={topArr} popoverPress={this._PopoverPress.bind(this)}/>
            </View>
        </Popover>
      </View>
    )
  }

  _renderScrollView() {
    return(
      <Animated.ScrollView style={{flex:1}}
        showsHorizontalScrollIndicator={false}  // 水平指示器
        showsVerticalScrollIndicator={false}    // 垂直指示器
        pagingEnabled={true}    // 开启分页功能
        alwaysBounceHorizontal={false} //弹性拉动一截
        scrollEnabled={this.state.scrollEnabled}
      >
        {this._renderHeader()}
        
      </Animated.ScrollView>
    )
  }

  _setScrollViewRef(ref) {
    if(ref && ref._component) {
        this._scrollView = ref._component;
    }
    else {
      this._scrollView = null;
    }
  }
  _getPage(index) {
    if(index === 0) {
      return(
        <QuanziPostListView pageData1={this.props.pageData} onRenderHeader={this._renderHeader.bind(this)} updateMark={this.state.updateMark} style={{paddingTop:Config.paddingTop,width:this._pageWidth,
          height:this._pageHeight}} noEmpty = {true} onScroll={this._onListViewScroll.bind(this)}
            pageData = {this.state.contentData} />
      )
    }
    else {
      return (
        <QZ_QunliaoListView updateMark={this.state.updateMark} style={{width:this._pageWidth,
          height:this._pageHeight}} noEmpty = {true} showCreate={true} onScroll={this._onListViewScroll.bind(this)}
            quanziData = {this.state.contentData} requestType={2}/>
      )
    }
  }

  _onListViewScroll(event) {
    // let y = event.nativeEvent.contentOffset.y;
    // this._tweenView(y);
  }

  _tweenView(y) {
    let headerTop = this._headerTop;
    let scrollViewTop = 0;
    if(y > 0) {
      headerTop = -this._headerHeight_1;
      // if(Platform.OS === "ios") {
        // headerTop += SizeUtils.translateDesignHeightToCode(40);
      // }
      // scrollViewTop = Config.statusBarHeight + SizeUtils.translateDesignHeightToCode(100);
      scrollViewTop = Config.paddingTop + this._headerHeight - this._headerHeight_1;
    }
    else if(y <= 0){
      headerTop = 0;
      scrollViewTop = Config.paddingTop + this._headerHeight;
    }
    if(headerTop != this._headerTop) {
      if(this._updateheaderTopTimer) {
        return;
      }
      this._updateheaderTopTimer = setTimeout(() => {
        this._clearUpdateheaderTopTimer();
      }, 1000);
      this._headerTop = headerTop;
      Animated.timing(                            // 随时间变化而执行的动画类型
        this.state.headerTop,                      // 动画中的变量值
        {
          toValue: headerTop,
        }
      ).start();
      Animated.timing(                            // 随时间变化而执行的动画类型
        this.state.scrollViewTop,                      // 动画中的变量值
        {
          toValue: scrollViewTop,
        }
      ).start();
    }
  }

  _clearUpdateheaderTopTimer() {
    this._updateheaderTopTimer && clearTimeout(this._updateheaderTopTimer);
    this._updateheaderTopTimer = null;
  }

   _renderHeader() {
    return(
      <View style={{backgroundColor:"#f96f67",}}>
        {this._renderQuanZiHeader()}
      </View>
    )
  }

  _renderQuanZiHeader(){
    if(this.state.contentData){
      return(
        <View style={{paddingTop:SizeUtils.translateDesignWidthToCode(13),
            marginLeft:SizeUtils.translateDesignWidthToCode(40),
            marginRight:SizeUtils.translateDesignWidthToCode(40),
        }}>
          <View
            style={{flexDirection:"row",
            marginTop:SizeUtils.translateDesignHeightToCode(20),
            }}>
              {this._renderHeaderImage()}
              <View style={{flex:1,
                marginLeft:SizeUtils.translateDesignWidthToCode(20),
                marginRight:SizeUtils.translateDesignWidthToCode(20),}}>
                <View style={{flexDirection:'row',alignItems: 'center',}}>
                  <Text style={{color:"#ffffff",flex:1,fontWeight:'bold',fontSize:SizeUtils.translateFontSizeToCode(32)}}>
                    {this.state.contentData.title}
                  </Text>
                  {this.state.contentData.is_admin===0?this._renderFavoritedButton():null}
                </View>
                <Text style={{marginTop:5,color:"#ffffff",fontSize:SizeUtils.translateFontSizeToCode(30)}}>
                  {this.state.contentData.desc}
                </Text>
                <View style={{marginTop:10,flexDirection:'row',alignItems: 'center',}}>
                  <View  style={{flex:1}}></View>
                  {this._BottomView(this.state.contentData)}
                </View>
              </View> 
          </View>
      </View>)
    }else{
      return(<View></View>)
    }
  }
  _BottomView=(data)=>(
    <View style={{flexDirection:'row',
        paddingLeft:SizeUtils.translateDesignWidthToCode(10),
        marginBottom:SizeUtils.translateDesignHeightToCode(14),alignItems: 'center',}}>
        <View style={{flexDirection:'row',alignItems: 'center',justifyContent: 'center',}}>
        <TImage source={require("../../../resource/images/activity/persion.png")} 
            style={{width:20,height:20,}}/>
        <Text  style={[CommonStyles.secondaryText,{color:'#fff',fontSize:SizeUtils.translateFontSizeToCode(24)}]}>
          {' '+(data.favoriters_num||0)}
        </Text>
        <TImage source={require("../../../resource/images/home/jianyi.png")} 
            style={{marginLeft:10,width:25,height:25,}}/>
        <Text  style={[CommonStyles.secondaryText,{color:'#fff',fontSize:SizeUtils.translateFontSizeToCode(24)}]}>
          {' '+(data.post_comment_num||0)}
        </Text>
      </View>
    </View> 
  );
  _renderFavoritedButton(){
        return (<TouchableOpacity onPress={this._shoucangQuanzi.bind(this)}
                        style={{backgroundColor: "transparent",borderRadius:SizeUtils.translateDesignNumToCode(44),alignItems:"center",justifyContent: 'center', borderWidth:SizeUtils.translateDesignNumToCode(3),
                  borderColor:"#fff", width:SizeUtils.translateDesignWidthToCode(140), height:SizeUtils.translateDesignHeightToCode(44),}}>
                      <Text style={{color:"#ffffff",fontSize:SizeUtils.translateFontSizeToCode(26)}}>
                      {this.state.contentData.is_favorited === 1?"退出圈子":"+加入"}
                      </Text>
                 </TouchableOpacity>)

  }

  _gotoMemberList(){
    this.gotoPage(Config.pages.quanzi_members,this.state.contentData);
  }

  _shoucangQuanzi(){
    new CommonCheckUserTypeAction().call(this, {needLogin:true, needVerify:true}, this._onCheckIsUserCallback.bind(this))
  }

  _onCheckIsUserCallback(result){
    if(result) {
          let msg = this.state.contentData.is_favorited === 1? "是否确定退出圈子？" : "是否确定加入圈子？";
    Alert.alert('提示', msg, [
        {text:'确定',onPress:()=>{
          new QuanziSendShoucangQuanziAction().call(this, {board_id:this.state.contentData.board_id})
        }},
        {text:'取消',onPress:()=>{}}
      ])
    }
  }


  _renderHeaderImage(){
     if(this.state.contentData.image_urls){
      return (<CommonAvatarView  avatarUri={this.state.contentData.image_urls[0]||''} size={100} />)
     }else{
        return (<CommonAvatarView avatarUri={require("../../../resource/images/quanzi/_tmp/02.png")}
                  size={100}/>)
     }
  }
  _showPopover(ref) {
    this._popoverbtn.measure((ox, oy, width, height, px, py) => {
      this._showMoreRightBtn({ x: px - 35, y: Platform.OS !== 'ios' ? py - 5 : py - 30, width: 0, height: 45 })
    })
  }
   _renderNavigationBarRightButtonContent() {
    var ishas = false;
    const user_id =this.props.pageData.routeData&&this.props.pageData.routeData.userData.user_id||'';
    if (this.state.detData&&user_id===this.state.detData.by_user_id) {
      ishas = true;
    }
    if (this.state.contentData.is_admin) {ishas = true;}
    return (
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <TouchableOpacity
          onPress={() => {
            this.gotoPage(Config.pages.qz_content_search, this.state.contentData);
          }}
          style={{ marginRight: 15 }}
        >
          <TImage source={require('../../../resource/images/workhard/search.png')} style={{ width: 34, height: 34 }} />
        </TouchableOpacity>
        {ishas?<TouchableOpacity
          ref={ref => (this._popoverbtn = ref)}
          onPress={() => {
            this._showPopover()
          }}
          style={{ marginRight: 0, marginLeft: 15 }}
        >
          <TImage
            source={require('../../../resource/images/quanzi/btn_more.png')}
            style={{ width: 34, height: 34 }}
            resizeMode={'contain'}
          />
        </TouchableOpacity>:null}
      </View>
    )
  }
  _renderWriteButton() {
    if(this.state.contentData.is_favorited === 1){
        return (
          <View style={{position:"absolute", bottom:0, right:0,
              width:SizeUtils.translateDesignWidthToCode(146),
              height:SizeUtils.translateDesignWidthToCode(146)}}>
            <TouchableOpacity onPress={this._onPressWriteButton.bind(this)}>
              <TImage source={require("../../../resource/images/quanzi/btn_comment.png")} style={{
                  width:106, height:106
              }} />
            </TouchableOpacity>
          </View>
        )

    }
  }

  _onPressWriteButton() {
    this.gotoPage(Config.pages.quanzi_write, {boardData:this.state.contentData});
  }

  _getTitle() {
    return this.state.contentData.title;
  }

 _getButtonTextStyle(index) {
    if(this.state.showType == index) {
      return style.btn_selected;
    }
    return style.btn_unselected;
  }

  _getButtonContainerStyle(index) {
    if(this.state.showType == index) {
      return style.container_selected;
    }
    return style.container_unSelected;
  }

  _onPressTypeBtn(index) {
    this._clickTopBtnTimer = setTimeout(() => {
      this.setState({
        scrollEnabled:Platform.OS === 'ios',
      });
      this._clearClickTopBtnTimer();
    }, 500);
    this.setState({
      scrollEnabled:true,
    }, ()=> {
      this._scrollTo({x:index * this._pageWidth});
    });
  }

  _scrollTo(params) {
    this._scrollView.scrollTo(params);
  }

  _clearClickTopBtnTimer() {
    this._clickTopBtnTimer && clearTimeout(this._clickTopBtnTimer)
    this._clickTopBtnTimer = null;
  }
}

let style = StyleSheet.create({
  container_selected: {
    borderBottomColor: "#db3132",
  },

  container_unSelected: {
  },

  btn_selected: {
    color: "#db3132",
  },

  btn_unselected: {
    color: "#999999",
  },
});
